#!/bin/python3
# -*- coding:utf-8 -*-
"""
    Syslog 服务
    Add By :陈狍子 e4ting@qq.com 2024-07-18 21:49:48
"""
import sys,os
from pdb import set_trace as strace
from traceback  import format_exc as dumpstack
from e4ting import util,log

import asyncio
import typing as t

import attr

@attr.s(auto_attribs=True)
class SyslogProtocol(asyncio.Protocol):
    """Syslog protocol support."""
    # server: 'SyslogServer' = attr.ib()
    # message_class = attr.ib()

    def datagram_received(self, data: bytes, addr: t.Tuple[str, int]):
        """Handle incoming package."""
        message = self.parse(data)
        log.info(f"<{addr}>:{message}")

    def parse(self, data: bytes):
        return data

async def start_udp_server():
    loop = asyncio.get_running_loop()
    transport, protocol = await loop.create_datagram_endpoint(
        lambda: SyslogProtocol(),
        local_addr=("0.0.0.0", 5140)  # 设置服务器监听的 IP 地址和端口
    )
    log.info("启动服务 0.0.0.0:5140")
    try:
        await asyncio.Future()  # 持续等待，直到手动中断程序
    except KeyboardInterrupt:
        pass
    finally:
        transport.close()

if __name__ == '__main__':
    asyncio.run(start_udp_server())
